package net.feling.hq711.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.ByteArrayInputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLHandler extends DefaultHandler {

	private List<HashMap<String, String>> mapList = null;
	private HashMap<String, String> map = null;
	private String currentTag = null;
	private String currentValue = null;
	private String nodeName = null;

	public XMLHandler(String _nodeName) {
		this.nodeName = _nodeName;
	}

	public List<HashMap<String, String>> getMapList() {
		return mapList;
	}

	@Override
	public void startDocument() throws SAXException {
		mapList = new ArrayList<HashMap<String, String>>();
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if (qName.equals(nodeName)) {
			map = new HashMap<String, String>();
		}
		if (attributes != null && map != null) {
			for (int i = 0; i < attributes.getLength(); i++) {
				map.put(attributes.getQName(i), attributes.getValue(i));
			}
		}
		currentTag = qName;
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (currentTag != null && currentValue != null) {
			map.put(currentTag, currentValue.trim());
			currentTag = null;
			currentValue = null;
		}
		if (qName.equals(nodeName)) {
			mapList.add(map);
			map = null;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String sch = new String(ch, start, length);
		if (currentValue == null) {
			currentValue = sch;
		} else {
			currentValue = currentValue + sch;
		}
	}

	/**
	 * 读取xml文件
	 * 
	 * @param Path_xmlfile
	 *            文件的路径
	 * @return 成功则返回列表（包含改文件内所有配置的map对象的列表），失败返回null
	 */
	public static List<HashMap<String, String>> execute(String xmlString,
			String _nodeName) {
		try {
			InputStream in = new ByteArrayInputStream(
					xmlString.getBytes("UTF8"));
			SAXParser saxparser = SAXParserFactory.newInstance().newSAXParser();
			XMLHandler xmlhadler = new XMLHandler(_nodeName);
			saxparser.parse(in, xmlhadler);
			return xmlhadler.getMapList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// public static void main(String[] args) {
	// String result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> "+
	// "<InfoList>"
	// + "<info url=\"/index.jsp\"><title>标题1</title><userface>"
	// + "/userface/defaut.jpg</userface><comefrom>校内办公 教务处</comefrom><time"
	// + ">2014-08-16 16:35</date></info>"
	//
	// + "</InfoList>";
	// xmlHandler.execute(result,"info");
	// }

}
